//201902104047周润恺
package cn.edu.sdjzu.xg.bysj.controller.basic;

import cn.edu.sdjzu.xg.bysj.domain.Student;
import cn.edu.sdjzu.xg.bysj.domain.Teacher;
import cn.edu.sdjzu.xg.bysj.service.StudentService;
import cn.edu.sdjzu.xg.bysj.service.TeacherService;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import lombok.extern.slf4j.Slf4j;
import util.Condition;
import util.ControllerHelper;
import util.JSONUtil;
import util.Pagination;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;
import java.util.Collection;
import java.util.List;

@WebServlet("/student.ctl")
@Slf4j
public class StudentController extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //创建JSON对象respMessage_jsonObj，以便往前端响应信息
        JSONObject respMessage_jsonObj = new JSONObject();
        //设置响应字符编码为UTF-8
        resp.setContentType("application/json;charset=UTF-8");
        //将request body转换为JSON字串
        String req_jsonStr = JSONUtil.getJSON(req);
        //将request body解析为JSONObject对象
        JSONObject req_jsonObj = JSON.parseObject(req_jsonStr);
        //如果请求body为空
        if (req_jsonObj == null) {
            respMessage_jsonObj.put("message","未收到请求信息！");
            resp.getWriter().println(respMessage_jsonObj);
            log.error("未收到请求信息");
            return;
        }
        //从JSONObject对象中读取键“id”的值（Java Object对象），req_jsonObj可能是{"id":1}
        Object id_obj = req_jsonObj.get("id");
        Object id_teacher = req_jsonObj.get("teacherId");
        try {
            //如果id_Obj != null, 说明请求数据有id键，是请求某个教师对象
            if (id_obj != null) {
                int id_int = Integer.parseInt(id_obj.toString());
                responseStudent(resp,id_int);
                log.trace("查找id为" + id_int + "的学生");
            } else if (id_teacher != null){
                Pagination pagination = ControllerHelper.getPagination(req_jsonObj);
                int teacher_id = Integer.parseInt(id_teacher.toString());
                this.responseStudents(resp, teacher_id, pagination);
                log.trace("根据老师查找学生");
            } else {
                //请求中包含条件和分页信息，需要响应多个教师对象
                //读取分页信息，形成分页对象
                //从JSONObject对象中读取 “pagination” 键对应的值(JSONObject对象)
                Pagination pagination = ControllerHelper.getPagination(req_jsonObj);
                //从请求JSONObject对象中读取键“condition”对应的值(描述查询条件的JSONArray对象)
                List<Condition> conditionList = ControllerHelper.getConditions(req_jsonObj);
                //响应多个教师信息，其中conditionList, pagination两个对象引用为空是可能的
                this.responseStudents(resp, conditionList, pagination);
                log.trace("条件分页查找老师");
            }
        } catch (SQLException e) {
            respMessage_jsonObj.put("message", "数据库操作异常");
            //响应respMessage_jsonObj到前端
            resp.getWriter().println(respMessage_jsonObj);
            log.error("数据库操作异常" + e.getMessage());
        } catch (Exception e) {
            respMessage_jsonObj.put("message", "网络异常");
            //响应respMessage_jsonObj到前端
            resp.getWriter().println(respMessage_jsonObj);
            log.error("网络异常" + e.getMessage());
        }
    }

    //按id查找学生
    private void responseStudent(HttpServletResponse response,int id) throws SQLException, IOException {
        Student student = StudentService.getInstance().find(id);
        String student_json = JSON.toJSONString(student);
        response.getWriter().println(student_json);
    }
    private void responseStudents(HttpServletResponse response, Collection<Condition> conditions, Pagination pagination) throws SQLException, IOException {
        //分页获得满足条件的所有
        Collection<Student> students = StudentService.getInstance()
                .findAll(conditions, pagination);
        //第二个参数可以防止循环引用
        String teachers_jsonStr = JSON.toJSONString(students,
                SerializerFeature.DisableCircularReferenceDetect);
        //创建JSON对象resp_jsonObj，以便往前端响应综合信息
        JSONObject resp_jsonObj = new JSONObject();
        resp_jsonObj.put("totalNum", pagination.getTotalNum());
        resp_jsonObj.put("data", teachers_jsonStr);
        //响应resp_jsonObj到前端
        response.getWriter().println(resp_jsonObj);
    }

    //根据老师查找老师下属的学生
    private void responseStudents(HttpServletResponse response,int teacher_id , Pagination pagination) throws SQLException, IOException {
        Teacher teacher = TeacherService.getInstance().find(teacher_id);
        Collection<Student> students = StudentService.getInstance().findAll(teacher,pagination);
        //第二个参数可以防止循环引用
        String teachers_jsonStr = JSON.toJSONString(students,
                SerializerFeature.DisableCircularReferenceDetect);
        //创建JSON对象resp_jsonObj，以便往前端响应综合信息
        JSONObject resp_jsonObj = new JSONObject();
        resp_jsonObj.put("totalNum", pagination.getTotalNum());
        resp_jsonObj.put("data", teachers_jsonStr);
        //响应resp_jsonObj到前端
        response.getWriter().println(resp_jsonObj);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //设置请求字符编码为UTF-8
        request.setCharacterEncoding("UTF-8");
        //设置响应字符编码为UTF-8
        response.setContentType("application/json;charset=UTF-8");
        //创建JSON对象respMessage_jsonObj，以便往前端响应信息
        JSONObject respMessage_jsonObj = new JSONObject();
        try {
            //根据request对象，获得代表新增Student的JSON字串
            String req_studentToAdd_jsonStr = JSONUtil.getJSON(request);
            log.trace(req_studentToAdd_jsonStr);
            //将JSON字串解析为Student对象
            Student studentToAdd = JSON.parseObject(req_studentToAdd_jsonStr,Student.class);
            log.trace(studentToAdd.toString());
            //在数据库表中增加Student对象
            StudentService.getInstance().add(studentToAdd);
            respMessage_jsonObj.put("message", "增加成功");
        } catch (SQLException e) {
            respMessage_jsonObj.put("message", "数据库操作异常");
            log.error("数据库操作异常" + e.getMessage());
        } catch (Exception e) {
            respMessage_jsonObj.put("message", "网络异常");
            log.error("网络异常" + e.getMessage());
        }
        //响应respMessage_jsonObj到前端
        response.getWriter().println(respMessage_jsonObj);
    }

    //修改表中数据
    @Override
    protected void doPut(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //设置请求字符编码为UTF-8
        request.setCharacterEncoding("UTF-8");
        String studentToUpdate_jsonStr = JSONUtil.getJSON(request);
        //将JSON字串解析为要修改的Student对象（有id的完整对象）
        Student studentToUpdate = JSON.parseObject(studentToUpdate_jsonStr, Student.class);
        //设置响应字符编码为UTF-8
        response.setContentType("application/json;charset=UTF-8");
        //创建JSON对象respMessage_jsonObj，以便往前端响应信息
        JSONObject respMessage_jsonObj = new JSONObject();
        try {
            //到数据库表修改Student对象对应的记录
            StudentService.getInstance().update(studentToUpdate);
            respMessage_jsonObj.put("message", "更新成功");
        } catch (SQLException e) {
            respMessage_jsonObj.put("message", "数据库操作异常");
            log.error("数据库操作异常" + e.getMessage());
        } catch (Exception e) {
            respMessage_jsonObj.put("message", "网络异常");
            log.error("网络异常" + e.getMessage());
        }
        //响应respMessage_jsonObj到前端
        response.getWriter().println(respMessage_jsonObj);
    }

    @Override
    protected void doDelete(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //将request参数转换为JSON字串
        String request_json_str = JSONUtil.getJSON(request);
        //将请求body解析为要删除的Student的id对应的JSONObject对象(可能是{"id":1})
        JSONObject idOfStudentToDelete_jsonObj = JSON.parseObject(request_json_str);
        //从JSONObject对象中读取键“id”的值（Java Object对象），
        Object id_obj = idOfStudentToDelete_jsonObj.get("id");
        int id_int = Integer.parseInt(id_obj.toString());
        log.trace("Student删除id" + id_int);
        //设置响应字符编码为UTF-8
        response.setContentType("application/json;charset=UTF-8");
        //创建JSON对象respMessage_jsonObj，以便往前端响应信息
        JSONObject respMessage_jsonObj = new JSONObject();
        try {
            //到数据库表中删除对应的教师
            StudentService.getInstance().delete(id_int);
            respMessage_jsonObj.put("message", "删除成功");
        } catch (SQLException e) {
            respMessage_jsonObj.put("message", "数据库操作异常");
            log.error("数据库异常" + e.getMessage());
        } catch (Exception e) {
            respMessage_jsonObj.put("message", "网络异常");
            log.error("网络异常" + e.getMessage());
        }
        //响应respMessage_jsonObj到前端
        response.getWriter().println(respMessage_jsonObj);
    }
}
